<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="100px">
      <el-row>
        <el-form-item label="评估类别" prop="pglb">
          <el-select v-model="queryParams.pglb" placeholder="请选择" @change="pglbChange" clearable>
            <el-option label="建筑物评估" value="建筑物评估"></el-option>
            <el-option label="生命线评估" value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-row v-if="queryParams.pglb!='1'">
        <el-form-item label="省" prop="provinceName">
          <el-select v-model="queryParams.provinceName" placeholder="请选择省" @change="chooseProvince" clearable
            value-key="name">
            <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="cityName">
          <el-select v-model="queryParams.cityName" placeholder="请选择市" @change="chooseCity" clearable value-key="name">
            <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区/县" prop="countyName">
          <el-select v-model="queryParams.countyName" placeholder="请选择区县" @change="chooseCounty" clearable
            value-key="name">
            <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="评估方法" prop="assessType" v-show="assessTypeDisabled">
          <el-select v-model="queryParams.assessType" placeholder="请选择" clearable>
            <el-option label="确定评估" value="0"></el-option>
            <el-option label="概率评估" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务编号" prop="assessCode">
          <el-input v-model="queryParams.assessCode" clearable />
        </el-form-item>
        <el-form-item label="任务名称" prop="assessName">
          <el-input v-model="queryParams.assessName" clearable />
        </el-form-item>
        <el-form-item label=" ">
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button plain @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-row>
      <el-form-item label=" " prop="level">
        <el-checkbox v-model="queryParams.level">包含下级</el-checkbox>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" ref="tableRef" :data="dataList" stripe>
      <el-table-column label="任务编号" prop="code" align="center" />
      <el-table-column label="任务名称" prop="name" align="center" min-width="200px" />
      <el-table-column label="评估类别" prop="pglb" align="center" width="120px">
        <template #default="{ row }">
          <span v-if="isBuilding">建筑物评估</span>
          <span v-else>生命线评估</span>
        </template>
      </el-table-column>
      <el-table-column label="评估方法" align="center" width="120px" v-if="isBuilding">
        <template #default="{ row }">
          <span>{{ assessType.find(item => item.value == row.assesstype || row.assessType)?.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="危险性数据" align="center" min-width="180px">
        <template #default="{ row }">
          <span v-if="isBuilding">
            {{
              row.inputmethod?.split(',')?.map(cur => {
                return seismicInputMode.find(item => item.value == cur)?.name
              }).join('、')
            }}
          </span>
          <span v-else>
            {{ inputMethods.find(item => item.value == row.inputMethod)?.name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="任务范围" prop="role" align="center" width="120px">
        <template #default="{ row }">
          <span v-if="row.role == roleValue">本级任务</span>
          <span v-if="Number(row.role) > Number(roleValue)">下级任务</span>
        </template>
      </el-table-column>
      <el-table-column label="省" prop="province" align="center" v-if="queryParams.pglb!='1'"/>
      <el-table-column label="市" prop="city" align="center" v-if="queryParams.pglb!='1'" />
      <el-table-column label="县" prop="county" align="center" v-if="queryParams.pglb!='1'" />
      <el-table-column label="操作" align="center" width="80px">
        <template #default="{ row }">
          <el-button type="text" @click="reporting(row)">报告</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination style="margin-top: 15px" v-show="total > 0" :total="total" v-model:page="queryParams.page"
      v-model:limit="queryParams.rows" @pagination="getList" ref="pagination" />
      
    <el-dialog title="生成评估报告" v-model="openLeader" append-to-body>
      <el-row :gutter="20" style="font-size:16px;text-align: center;margin:10px 0 20px 0">
        <el-col :span="12"><strong>当前任务编号：{{ taskCode }}</strong></el-col>
        <el-col :span="12"><strong>当前任务名称：{{ taskName }}</strong></el-col>
      </el-row>
      <el-table :data="leaderList" stripe v-if="isBuilding">
        <el-table-column label="危险性数据" align="center" prop="type_name" width="150" />
        <el-table-column label="系统生成" align="center" prop="generated">
          <template #default="{ row }">
            <p v-if="row.report_file_name" style="width: 100%">
              <el-link :underline="false" type="primary" @click="downloadReport(row.report_file_id)" class="ellipsis-link">
                {{ row.report_file_name }}
              </el-link>
            </p>
            <p>
              <el-link v-if="row.report_file_name == '' || row.report_file_name == null" :underline="false" type="primary"
                @click="createReport(row)">
                生成报告
              </el-link>
              <el-link v-else :underline="false" type="primary" @click="createReport(row)">重新生成</el-link>
            </p>
          </template>
        </el-table-column>
        <el-table-column label="终版上传" align="center" prop="dataUpload">
          <template #default="{ row }">
            <p v-if="row.final_report_file_name" style="width: 100%">
              <el-link :underline="false" type="primary" @click="downloadReport(row.final_report_file_id)" class="ellipsis-link">
                {{ row.final_report_file_name }}
              </el-link>
            </p>
            <p>
              <el-link v-if="row.final_report_file_name == '' || row.final_report_file_name == null" :underline="false"
                type="primary" @click="uploadReport(row)">
                上传
              </el-link>
              <el-link v-else :underline="false" type="primary" @click="uploadReport(row)">重新上传</el-link>
            </p>
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="center" prop="create_user" width="180" />
        <el-table-column label="创建时间" align="center" prop="create_time" width="160" />
      </el-table>
      <el-table :data="leaderList" stripe v-else>
        <el-table-column label="危险性数据" align="center" prop="inputMethod" width="120px">
          <template #default="{ row }">
            <span>{{ inputMethods.find(item => item.value == row.inputMethod)?.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="系统生成" align="center" prop="createReportName">
          <template #default="{ row }">
            <p v-if="row.createReportName" style="width: 100%">
              <el-link :underline="false" type="primary" @click="downloadReport(row.createReport)" class="ellipsis-link">
                {{ row.createReportName }}
              </el-link>
            </p>
            <p>
              <el-link v-if="row.createReport" :underline="false" type="primary" @click="createReport(row)">重新生成</el-link>
              <el-link v-else :underline="false" type="primary" @click="createReport(row)">生成报告</el-link>
            </p>
          </template>
        </el-table-column>
        <el-table-column label="终版上传" align="center" prop="uploadReportName">
          <template #default="{ row }">
            <p v-if="row.uploadReportName" style="width: 100%">
              <el-link :underline="false" type="primary" @click="downloadReport(row.uploadReport)" class="ellipsis-link">
                {{ row.uploadReportName }}
              </el-link>
            </p>
            <p>
              <el-link v-if="row.uploadReport" :underline="false" type="primary" @click="uploadReport(row)">重新上传</el-link>
              <el-link v-else :underline="false" type="primary" @click="uploadReport(row)">上传</el-link>
            </p>
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="center" prop="createReportUser" width="120px" />
        <el-table-column label="创建时间" align="center" prop="createReportTime" width="160px" />
      </el-table>
      <template #footer>
        <div class="dialog-footer" style="text-align: right;margin-right:20px">
          <el-button plain @click="openLeader = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <UploadDoc v-model:open="uploadOpen" :file="['doc', 'docx']" :limit="1" @confirm="confirm" />
  </div>
</template>
<script setup>
import { getProvince, getChildArea } from "@/api/system/division";
import { getCurRole, getPage, getReportData, generateWordReportData, updateTaskReportData, createReportData, updateLifeReportData } from '@/api/searchExport/report/reportGenerate'
import UploadDoc from '../components/upload.vue'
import { seismicInputMode, assessType } from '@/views/building'
import { inputMethods } from '@/views/lifelineProject'

const { proxy } = getCurrentInstance()
const data = reactive({
  queryParams: {
    provinceName: '',
    cityName: '',
    countyName: '',
    pglb: '建筑物评估',
    assessType: '0',
    assessCode: '',
    assessName: '',
    page: 1,
    rows: 10,
    level: true
  },
})
const { queryParams } = toRefs(data);
const loading = ref(false)
const dataList = ref([])
const openLeader = ref(false)
const leaderList = ref([])
const provinceData = ref([])
const cityData = ref([])
const areaData = ref([])
const total = ref(0)
const taskCode = ref('')
const taskName = ref('')
const isBuilding = computed(() => queryParams.value.pglb == '建筑物评估')

// 评估类别切换
const assessTypeDisabled = ref(true)
const pglbChange = val => {
  if (val == '1') {
    proxy.resetForm('queryRef')
    queryParams.value.province=''
    queryParams.value.county=''
    queryParams.value.city=''
    queryParams.value.pglb=val
    queryParams.value.assessType = null
    assessTypeDisabled.value = false
  } else {
    queryParams.value.assessType = '0'
    assessTypeDisabled.value = true
  }
  getList()
}

// 获取角色
const roleValue = ref('')
const getRoleInfo = async () => {
  const { data: { role, provinceId, cityId, countyId } } = await getCurRole()
  roleValue.value = role
  switch (role) {
    case '0':
      getProvinceData()
      getList()
      break;
    case '1':
      filterProvinceOption(provinceId, getList)
      chooseProvince(provinceId)
      break;
    case '2':
      filterProvinceOption(provinceId)
      filterCityOption(provinceId, cityId, getList)
      chooseCity(cityId)
      break;
    case '3':
      filterProvinceOption(provinceId)
      filterCityOption(provinceId, cityId)
      filterCountyOption(cityId, countyId, getList)
      break;
    default:
      break;
  }
}

function reporting(row) {
  openLeader.value = true
  const { code, name } = row
  taskCode.value = code
  taskName.value = name
  if (isBuilding.value) {
    getReportList(row.id)
  } else {
    leaderList.value = [row]
  }
}
const getReportList = id => {
  getReportData({ taskId: id }).then(res => {
    leaderList.value = res.data.reportList
  }).catch()
}
// 建筑物 provinceName cityName countyName 实际传的是id
// 生命线 province city county 实际传的是name
// 获取省列表
function getProvinceData() {
  getProvince().then((response) => {
    provinceData.value = response.data;
  });
}
//选择省
function chooseProvince(value) {
  cityData.value = [];
  areaData.value = [];
  queryParams.value.countyName = null
  queryParams.value.cityName = null
  queryParams.value.province = provinceData.value.find(item => item.id == value)?.name
  queryParams.value.county = null
  queryParams.value.city = null
  getChildArea(value).then(response => {
    cityData.value = response.data
  });
}
//选择市
function chooseCity(value) {
  queryParams.value.countyName = null
  queryParams.value.city = cityData.value.find(item => item.id == value)?.name
  queryParams.value.county = null
  areaData.value = [];
  getChildArea(value).then((response) => {
    areaData.value = response.data
  })
}
//选择区县
function chooseCounty(value) {
  queryParams.value.county = areaData.value.find(item => item.id == value)?.name
}
const filterProvinceOption = async (provinceId, cb) => {
  getProvince().then(res => {
    const nodes = res.data.filter(item => item.value == provinceId)
    provinceData.value = nodes
    queryParams.value.provinceName = provinceId
    queryParams.value.province = provinceData.value.find(item => item.id == provinceId)?.name
    cb && cb()
  })
}
const filterCityOption = (provinceId, cityId, cb) => {
  getChildArea(provinceId).then(res => {
    const nodes = res.data.filter(item => item.id == cityId)
    cityData.value = nodes
    queryParams.value.cityName = cityId
    queryParams.value.city = cityData.value.find(item => item.id == cityId)?.name
    cb && cb()
  })
}
const filterCountyOption = (cityId, countyId, cb) => {
  getChildArea(cityId).then(res => {
    const nodes = res.data.filter(item => item.id == countyId)
    areaData.value = nodes
    queryParams.value.countyName = countyId
    queryParams.value.county = areaData.value.find(item => item.id == countyId)?.name
    cb && cb()
  })
}

// 查询
const handleQuery = () => {
  getList()
}

// 重置
const resetQuery = () => {
  proxy.resetForm('queryRef')
  queryParams.value.province=''
  queryParams.value.county=''
  queryParams.value.city=''
  assessTypeDisabled.value = true
  getRoleInfo()
}

const getList = () => {
  loading.value = true
  getPage({ ...queryParams.value, role: roleValue.value }, queryParams.value.pglb).then(res => {
    dataList.value = res.data?.rows || []
    total.value = res.data?.total || 0
    loading.value = false
  })
}

// 上传
const uploadOpen = ref(false)
const templateId = ref()
const taskId = ref('')
// 上传、重新上传
const uploadReport = row => {
  uploadOpen.value = true
  templateId.value = row.id
  taskId.value = row.task_id
}

const confirm = (file) => {
  if (isBuilding.value) {
    updateTaskReportData({ dataId: templateId.value, finalReportFileId: file.attachId }).then(res => {
      if (res.code == 200) {
        proxy.$modal.msgSuccess('上传成功！')
        templateId.value = ''
        uploadOpen.value = false
        getReportList(taskId.value)
      }
    })
  } else {
    const { attachId, attachName } = file
    console.log(file, attachId, attachName)
    updateLifeReportData({ id: templateId.value, uploadReport: attachId, uploadReportName: attachName }).then(res => {
      if (res.code == 200) {
        proxy.$modal.msgSuccess('上传成功！')
        uploadOpen.value = false
        const { uploadReport, uploadReportName } = res.data
        leaderList.value = [{ ...leaderList.value[0], uploadReport, uploadReportName }]
      }
    })
  }
}

// 下载
const downloadReport = fileId => {
  location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(fileId);
}
// 生成报告、重新生成
function createReport(row) {
  proxy.$modal.loading('正在生成报告，请稍等...')
  if (isBuilding.value) {
    generateWordReportData({ dataId: row.id, taskId: row.task_id, typeId: row.type_id }).then(res => {
      proxy.$modal.closeLoading()
      proxy.$modal.msgSuccess(res.data)
      getReportList(row.task_id)
    }).catch(() => {
      proxy.$modal.closeLoading()
      proxy.$modal.msgError('生成失败！')
    })
  } else {
    createReportData(row.id).then(res => {
      proxy.$modal.closeLoading()
      const { createReport, createReportName, createReportTime, createReportUser } = res.data
      leaderList.value = [{ ...leaderList.value[0], createReport, createReportName, createReportTime, createReportUser }]
      proxy.$modal.msgSuccess('生成成功！')
    }).catch(() => {
      proxy.$modal.closeLoading()
      proxy.$modal.msgError('生成失败！')
    })
  }
}
onMounted(() => {
  getRoleInfo()
})
</script>

<style lang="scss" scoped>
:deep(.ellipsis-link) {
  width: 100%;
  &>.el-link__inner{
    width: 100%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: inline-block;
  }
}
</style>